<script setup>
import LfDropdownPanel from '@/components/commonUI/LfDropdownPanel.vue'
import UserAvatarContent from './UserAvatarContent.vue'
import { useRouter } from 'vue-router'
import { userCenterStore } from '@/stores/userCenterStore'
import { useGlobalStore } from '@/stores/globalStore'
import { getToken } from '@/utils/webStorage'

const props = defineProps({
  avatar: String,
  userId: Number,
  username: String,
  size: {
    type: String,
    default: '40',
  },
  trigger: {
    type: String,
    default: 'click',
  },
  noDropdown: {
    type: Boolean,
    default: false,
  },
})

const router = useRouter()

const dropdownRef = ref(null)

const handleClose = () => {
  dropdownRef.value.hidePanel()
}

const navToUserHome = (activeIndex) => {
  if (getToken()) {
    router.push(`/user/${props.userId}`)
    userCenterStore().setActiveIndex(activeIndex)
  } else {
    useGlobalStore().showLogin()
  }
}
</script>

<template>
  <div v-if="noDropdown"  @click="navToUserHome(0)">
    <img
      :src="avatar"
      alt=""
      class="rounded-full cursor-pointer object-cover"
      :style="{ width: size + 'px', height: size + 'px' }" />
  </div>

  <LfDropdownPanel
    v-else
    :trigger="trigger"
    position="right"
    ref="dropdownRef"
    class="flex-shrink-0"
    :style="{ width: size + 'px', height: size + 'px' }"
    needLogin>
    <div v-if="username" class="text-sm whitespace-nowrap">{{ username }}</div>
    <img
      v-else
      :src="avatar"
      alt=""
      class="rounded-full cursor-pointer object-cover"
      :style="{ width: size + 'px', height: size + 'px' }" />

    <template #content>
      <UserAvatarContent :userId="userId" @close="handleClose" />
    </template>
  </LfDropdownPanel>
</template>
